<template>
  <!-- 添加或者修改SPU -->
  <el-card style="margin-top: 20px" v-else>
    <el-form label-width="100px">
      <el-form-item label="SKU名称">
        <span>{{ spuData.spuName }}</span>
      </el-form-item>

      <el-form-item label="SPU名称">
        <el-input v-model="formData.skuName" placeholder="SKU名称"></el-input>
      </el-form-item>

      <el-form-item label="价格">
        <el-input-number
          v-model="formData.price"
          :min="0"
          label="价格"
        ></el-input-number>
      </el-form-item>

      <el-form-item label="重量">
        <el-input-number
          v-model="formData.weight"
          :min="0"
          label="重量"
        ></el-input-number>
      </el-form-item>

      <el-form-item label="规格描述">
        <el-input
          v-model="formData.skuDesc"
          placeholder="规格描述"
          type="textarea"
          rows="4"
        ></el-input>
      </el-form-item>

      <el-form-item label="平台属性">
        <!-- 属性表单 -->
        <el-form inline label-width="100px">
          <el-form-item
            :label="attr.attrName"
            v-for="(attr, index) in attrList"
            :key="attr.id"
          >
            <el-select placeholder="请选择" v-model="attrSelectList[index]">
              <el-option
                :label="attrValue.valueName"
                :value="`{\&quot;attrId\&quot;:${attrValue.attrId},\&quot;valueId\&quot;:${attrValue.id}}`"
                v-for="attrValue in attr.attrValueList"
                :key="attrValue.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>

      <el-form-item label="销售属性">
        <el-form inline label-width="100px">
          <el-form-item
            :label="sale.saleAttrName"
            v-for="(sale, index) in saleAttrList"
            :key="sale.id"
          >
            <el-select v-model="saleAttrSelectList[index]" placeholder="请选择">
              <el-option
                v-for="saleValue in sale.spuSaleAttrValueList"
                :key="saleValue.id"
                :value="`${saleValue.baseSaleAttrId}|${saleValue.id}`"
                :label="saleValue.saleAttrValueName"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>

      <el-form-item label="图片列表">
        <el-table :data="spuImgList" border @selection-change="selectImg">
          <el-table-column type="selection" width="55" align="center">
          </el-table-column>
          <el-table-column label="图片" align="center">
            <template slot-scope="{ row }">
              <el-image :src="row.imgUrl" style="height: 150px"></el-image>
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="imgName"> </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="{ row }">
              <el-button
                v-if="!row.isDefault"
                type="primary"
                @click="defaultImg(row)"
                >设为默认</el-button
              >
              <el-tag v-else type="warning">默认</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="save">保存</el-button>
        <el-button @click="gotoSpuList">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { reqAttrData } from "@/api/platformAttr";
import { mapState } from "vuex";
import { reqSpuImageList, reqSpuSaleAttrList } from "@/api/spu";
import { reqAddSku } from "@/api/sku";

export default {
  name: "AddSku",
  props: ["spuData"],
  data() {
    return {
      formData: {
        spuId: 0,
        tmId: 0,
        category3Id: 0,
        skuName: "",
        price: "",
        weight: "",
        skuDesc: "",
        skuDefaultImg: "",
        skuImageList: [
          {
            id: 0,
            spuId: 0,
            imgName: "",
            imgUrl: "",
            isDefault: "",
          },
        ],
        skuAttrValueList: [
          {
            attrId: "",
            valueId: "",
          },
        ],
        skuSaleAttrValueList: [
          {
            saleAttrId: "",
            saleAttrValueId: "",
          },
        ],
      },
      attrList: [],
      saleAttrList: [],
      spuImgList: [],
      attrSelectList: [],
      saleAttrSelectList: [],
      formAttrList: [],
      formImgList: [],
    };
  },

  watch: {
    attrSelectList: {
      handler(newValue) {
        // 返回存在的,然后让里面的每一项解析成对象
        this.formAttrList = newValue
          .filter((item) => item)
          .map((item) => JSON.parse(item));
      },
    },
  },

  mounted() {
    this.getAttrList();
    this.getSpuSaleAttrList();
    this.getImageList();
    console.log(this.spuData);
  },

  computed: {
    ...mapState({
      category1Id: (state) => state.category.category1Id,
      category2Id: (state) => state.category.category2Id,
      category3Id: (state) => state.category.category3Id,
    }),
  },

  methods: {
    // 回到列表页面
    gotoSpuList() {
      this.$emit("goto");
    },

    // 获取平台属性列表
    async getAttrList() {
      this.attrList = [];

      if (this.category3Id !== "") {
        try {
          const res = await reqAttrData(
            this.category1Id,
            this.category2Id,
            this.category3Id
          );
          this.attrList = res.data;
          // this.$message.success("获取属性列表数据成功");
        } catch (error) {
          console.log(error);
          this.$message.error("获取属性列表数据失败");
        }
      }
      this.loading = false;
    },

    // 获取销售属性列表
    async getSpuSaleAttrList() {
      try {
        const res = await reqSpuSaleAttrList(this.spuData.id);
        this.saleAttrList = res.data;
      } catch (error) {
        console.log(error);
        this.$message.error("获取销售属性列表数据失败");
      }
    },

    // 获取图片列表
    async getImageList() {
      try {
        const res = await reqSpuImageList(this.spuData.id);
        this.spuImgList = res.data;
        this.spuImgList = this.spuImgList.map((item) => {
          return {
            ...item,
            isDefault: false,
          };
        });
      } catch (error) {
        console.log(error);
        this.$message.error("获取属性列表数据失败");
      }
    },

    // 设置默认图片
    defaultImg(row) {
      this.spuImgList.forEach((item) => {
        item.isDefault = row.id == item.id;
      });
      this.formData.skuDefaultImg = row.imgUrl;
    },

    // 选择图片
    selectImg(data) {
      this.formImgList = data;
    },

    // 保存
    async save() {
      this.formData.skuSaleAttrValueList = this.saleAttrSelectList.map(
        (item) => {
          const [saleAttrId, saleAttrValueId] = item.split("|");
          return {
            saleAttrId,
            saleAttrValueId,
          };
        }
      );
      this.formData = {
        ...this.formData,
        category3Id: this.category3Id,
        spuId: this.spuData.id,
        tmId: this.spuData.tmId,
        skuImageList: this.formImgList,
        skuAttrValueList: this.formAttrList,
      };

      try {
        const res = await reqAddSku(this.formData);
        this.$message.success("添加SKU成功");
        // 跳转到首页
        this.$emit("goto");
      } catch (error) {
        console.log(error);
        this.$message.error("添加SKU失败");
      }
    },
  },
};
</script>

<style lang="scss" scoped></style>
